package com.haierp.controller.purchase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.haierp.dto.TaskPurchaseDTO;
import com.haierp.enums.GeneralStatus;
import com.haierp.model.ItemSku;
import com.haierp.model.purchase.Receipt;
import com.haierp.model.purchase.TaskPurchase;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.purchase.ITaskPurchaseService;
import com.haierp.util.JsonResult;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.BeanUtils;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

/**
 * 采购流水
 * @author zhulu
 *
 */
@Controller
@RequestMapping("/taskPurchase")
public class TaskPurchaseController extends BaseController{

	@Autowired
	private ITaskPurchaseService taskPurchaseService;
	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	
	/**
	 * 增加流水任务
	 * @param taskPurchase
	 * @return
	 */
	@RequestMapping("/queryTaskPurchaseList")
	@ResponseBody
	public Object queryTaskPurchaseList(Integer status) {
		JsonResult<List<TaskPurchaseDTO>> result = new JsonResult<>();
		ShiroUser user = getShiroUser();
		List<TaskPurchase>  tps = taskPurchaseService.queryTaskPurchaseList(user.getId(),status);
		List<TaskPurchaseDTO>  tpDtos = new ArrayList<>();
		if(tps!=null&&!tps.isEmpty()){
			tps.forEach(
					tp->{
						 TaskPurchaseDTO taskPurchaseDTO = new TaskPurchaseDTO();
						 BeanUtils.copy(tp, taskPurchaseDTO);
						 ItemSku itemSku = itemSkuService.selectById(tp.getSkuId());
				    	 if(itemSku!=null){
				    		 taskPurchaseDTO.setItemName(itemSku.getItemName());
				    	 }
				    	 tpDtos.add(taskPurchaseDTO);
					}
				);
			
		}
		return result.buildIsSuccess(true).buildData(tpDtos);
	}
	
	/**
	 * 增加流水任务
	 * @param taskPurchase
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Object queryTaskPurchase(Long id) {
		JsonResult<TaskPurchaseDTO> result = new JsonResult<>();
	     TaskPurchase tp = taskPurchaseService.selectById(id);
	     TaskPurchaseDTO taskPurchaseDTO = new TaskPurchaseDTO();
	     if(tp!=null){
	    	 BeanUtils.copy(tp, taskPurchaseDTO);
	    	 ItemSku itemSku = itemSkuService.selectById(tp.getSkuId());
	    	 if(itemSku!=null){
	    		 taskPurchaseDTO.setItemName(itemSku.getItemName());
	    	 }
	     }
		return result.buildIsSuccess(true).buildData(taskPurchaseDTO);
	}
	
	/**
	 * 增加流水任务
	 * @param taskPurchase
	 * @return
	 */
	@RequestMapping("/confirm")
	@ResponseBody
	public Object confirm(Long id,Integer quantity,Double price) {
		JsonResult<String> result = new JsonResult<>();
		if(id==null||quantity==null||price==null){
			 return result.buildIsSuccess(false).buildData("没有传数量或者价格");	
		}
	     TaskPurchase tp = taskPurchaseService.selectById(id);
	     if(tp!=null){
	    	 TaskPurchase tpUpdate = new TaskPurchase();
	    	 tpUpdate.setGmtModify(new Date());
	    	 tpUpdate.setId(tp.getId());
	    	 tpUpdate.setQuantity(quantity);
	    	 tpUpdate.setStatus(GeneralStatus.CONFIRM.getCode());
	    	 tpUpdate.setPrice(price);
	    	 taskPurchaseService.updateSelectiveById(tpUpdate);
	    	 return result.buildIsSuccess(true);
	     }else{
	    	 return result.buildIsSuccess(false).buildData("没有找到");
	     }
	}
	
	/**
	 * 创建小票
	 * @param taskPurchase
	 * @return
	 */
	@RequestMapping("/createReceipt")
	@ResponseBody
	public Object createReceipt(String taskIds) {
		JsonResult<String> result = new JsonResult<>();
		if(taskIds!=null){
			//1 数据格式和流水状态校验
			  String s = taskIds.replace("&quot;", "\"");
			  List<Long> a =  HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
			  List<TaskPurchase> tps = taskPurchaseService.selectBatchIds(a);
			  double totalPrice = 0.0d;
			  Long buyerId = 0l;
			  for(TaskPurchase tp:tps){
				  if(tp.getStatus()!=GeneralStatus.CONFIRM.getCode()){
					  return result.buildIsSuccess(false).buildData("有流水单状态错误");
				  }else{
					  buyerId = tp.getBuyerId();
					  totalPrice+=tp.getPrice()*tp.getQuantity();
				  }
			  }
			//根据流水生成小票
			  Receipt receipt = new Receipt();
			  receipt.setGmtCreate(new Date());
			  receipt.setGmtModify(new Date());
			  receipt.setReceiptNo("RECO"+sequenceUtilService.gainRECOSequence());
			  receipt.setStatus(GeneralStatus.INIT.getCode());
			  receipt.setTotalPrice(totalPrice);
			  receipt.setBuyerId(buyerId);
			//保存小票到数据库，更新流水单的状态
			  try {
				taskPurchaseService.createReceipt(receipt, tps);
			} catch (Exception e) {
				e.printStackTrace();
				result.buildIsSuccess(false).buildMsg(e.getMessage());
			}
		}
		return result.buildIsSuccess(true);

	}

}
